﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Configuration;
using System.Collections.Specialized;
using MarginTrading.Entity;
using MarginTrading.Services;


namespace Dataloading
{
    public partial class Form1 : Form
    {
        String TrHdrFile = "D:\\ats2_ttr.hdr";
        String CDSTranHdrFile = "D:\\CDS_Tran.hdr";
        String BROKER_CODE = "DSA";
        String[] AgentsList = {"aa", "aaa"};
        public Form1()
        {
            InitializeComponent();
            
            foreach (String Agent in AgentsList)
            {
                AgentCheckBox.Items.Add(Agent);
            }
                
        }


    

        private void button1_Click(object sender, EventArgs e)
        {
            Stream myStream = null;

            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = "D:\\";
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {

                    //AtsHdrTxtBox.Text = openFileDialog1.FileName;

                    if ((myStream = openFileDialog1.OpenFile()) != null)
                    {
                        using (myStream)
                        {
                            // Insert code to read the stream here.
                        }
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
         
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = "D:\\";
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    AtsDataTxtBox.Text = openFileDialog1.FileName;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }

        }

        private void CDSDataBrws_Click(object sender, EventArgs e)
        {
             OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = "D:\\";
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    CDSDataTxtBox.Text = openFileDialog1.FileName;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

        private void Upload_Click(object sender, EventArgs e)
        {
            
            //ReadTradeHdrFile(AtsHdrTxtBox.Text);
            //ReadTradeFile();
            //CDSTranDataFile();
    
        }
        int LineWidth = 0;
        static Dictionary<String, int> mapOffset = new Dictionary<String, int>();
        static Dictionary<String, int> mapSize = new Dictionary<String, int>();



        void ReadTradeHdrFile(String FilePath, int StartRow)
        {
            try
            {
                mapOffset.Clear();
                mapSize.Clear();
                string[] lines = System.IO.File.ReadAllLines(FilePath);
                int count = 0;
                int Offset = 0;
                System.Console.WriteLine("No of Lines :" + lines.Length);
                foreach (string line in lines)
                {
                    count++;
                    if (count < StartRow)
                        continue;

                    String ClmName = line.Substring(0, 20).Trim();
                    String size = line.Substring(32, 2);
                    int iSize = 0;
                    try
                    {
                        iSize = Int16.Parse(size);

                    }
                    catch (Exception ee)
                    {
                        continue;
                    }
                    mapSize.Add(ClmName, iSize);
                    mapOffset.Add(ClmName, Offset);

                    Console.WriteLine(ClmName + " " + iSize + " " + Offset);
                    Offset = iSize + Offset;


                }
                LineWidth = Offset;

                System.Console.WriteLine("No of ele :" + mapOffset.Count() + "   " + count);
            }
            catch (Exception fileEx)
            {
                MessageBox.Show(fileEx.Message);
            }

        }

        List<String> SymbolList = new List<String>();

        void ReadTradeFile(String AgentCode)
        {
            try
            {

                List<String> ClientsList = ClientService.GetClientCodeCollection();
                SymbolList.Clear();
                SymbolList = SecurityServices.GetSecSymbolList();
                
                progressBar1.Value = progressBar1.Minimum;
                string[] lines = System.IO.File.ReadAllLines(AtsDataTxtBox.Text);
                int count = 0;
                System.Console.WriteLine("No of Lines :" + lines.Length);
             
                String[] TaxsFees = null;
                try
                {
                     TaxsFees = ConfigurationSettings.AppSettings.AllKeys;
                }
                catch(Exception er)
                {
                    MessageBox.Show("Error in App.config file.");
                    return;
                }          

                foreach (string line in lines)
                {
                    count++;
                    //Checking the length of a line
                    if (line.Length != LineWidth)
                    {
                        MessageBox.Show("Error in Line " + count + " of the ats2_ttr data file.\n"+
                                       "Please check the file and try again.");
                        return;

                    }

                    int Quan = Int32.Parse(GetValue("quantity", line));
                    Double Price = Double.Parse(GetValue("price", line));

                    //Trading date has to be matched with the date in the file.
                    //if (GetValue("trade_date", line).CompareTo(TrDate.Value.ToString("yyyy/MM/dd")) != 0 )
                    //{
                    //    MessageBox.Show("Trading date mismatch");
                    //    return;
                    //}

                    if (count == ((count / (lines.Length / 100)) * (lines.Length / 100)))
                        ProBar_();

                    String JointACNo = GetValue("joint_ac_no", line);
                    if (JointACNo.Length == 1)
                        JointACNo = "0" + JointACNo;

                    String ClientCode = GetValue("participant id", line) + "-" +
                                        GetValue("client_prefix", line) + "-" +
                                        GetValue("client_suffix", line) + "-" +
                                        JointACNo;
                    String CompanySymbol = GetValue("company_id", line) + "-" +
                                                                GetValue("main_type", line) + "-" +
                                                                GetValue("sub_type", line);
                    
                    UpdateSecurity(CompanySymbol);

                    if (!ClientsList.Contains(ClientCode)) 
                    {
                        continue;
                    }
                                   

                    Double Amount = Quan * Price;

                    double TotalTax = 0;
                    foreach(String tax in TaxsFees)
                    {
                        TotalTax = TotalTax + Double.Parse(GetValue(tax, line));

                    } 
                    if (GetValue("buy_sell", line) == "S" )
                    {
                        Quan = Quan * -1;
                        Amount = Amount - TotalTax;
                    }
                    else
                    {
                        Amount = Amount + TotalTax;
                    }

                    Updateportfolio(ClientCode, CompanySymbol, Quan);   

                    LogBox.AppendText(ClientCode + " : " + Amount + "\n");
                    DailyTransactions DailyTr = new DailyTransactions();
                    try
                    {
                        DailyTr.TradeDate           = DateTime.Parse(GetValue("trade_date", line) +" "+ GetValue("trade_time", line));
                        
                        DailyTr.TranId              = GetValue("tran_id", line);
                        DailyTr.ExecutionId         = GetValue("execution_id", line);
                        DailyTr.BuySell             = GetValue("buy_sell", line);
                        DailyTr.CompanySymbol       = CompanySymbol;
                        DailyTr.Quantity            = Int32.Parse(GetValue("quantity", line));
                        DailyTr.Price               = double.Parse(GetValue("price", line));
                        DailyTr.TaxFlag             = Int32.Parse(GetValue("tax_flag", line));
                        DailyTr.BrokerIdBuy         = GetValue("broker_id_buy", line);
                        DailyTr.BrokerIdSell        = GetValue("broker_id_sell", line);
                        DailyTr.BuyingContractNo    = Int32.Parse(GetValue("buying_contract_no", line));
                        DailyTr.SellingContractNo   = Int32.Parse(GetValue("selling_contract_no", line));
                        DailyTr.ClientCode          = ClientCode;
                        DailyTr.ParticipantId       = GetValue("participant id", line);
                        DailyTr.ForeignFlag         = Int32.Parse(GetValue("foreign_flag", line));
                        DailyTr.Amount              = Amount;
                        DailyTr.OrderId             = GetValue("order_id", line);
                        DailyTr.Status              = Int32.Parse(GetValue("status", line));                      
                        
                        DailyTransactionsServices.Add(DailyTr);
                    }
                    catch (System.Data.OracleClient.OracleException)
                    {
                        LogBox.AppendText("Transaction record already exist.( Exec ID -" + GetValue("execution_id", line) + " )\n");
                    }
                    
                    //writing to the DB                   
                  

                }
                //System.Console.WriteLine("No of records :" + count);
                
              
            }
            catch (Exception fileEx)
            {
                //throw;
                MessageBox.Show(fileEx.Message);
            }
        }

        //Generating files for margin agents
        void GenerateDataFiles(String AgentCode, String FileType, String FilePath )
        {
            try
            {
                //List<String> ClientsList = ClientsUnderAgent(AgentCode);
                List<String> ClientsList = ClientService.GetClientCodeCollection(AgentCode);

                progressBar1.Value = progressBar1.Minimum;
                string[] lines = System.IO.File.ReadAllLines(FilePath);
                int count = 0;
                int RecCount = 0;

                String date = TrDate.Value.ToString("ddMMyyyy");
                System.IO.StreamWriter file = new System.IO.StreamWriter("D:\\" + AgentCode + "_"+ FileType +"_"+ date + ".txt");

                file.WriteLine(AgentCode + "|" + FileType );
                foreach (string line in lines)
                {
                    count++;
                    //Checking the length of a line
                    if (line.Length != LineWidth)
                    {
                        MessageBox.Show("Error in Line " + count + " of the ats2_ttr data file.\n" +
                                       "Please check the file and try again.", "Error in file");
                        file.Close();
                        return;
                    }

                    //Trading date has to be matched with the date in the file.
                   /* if (GetValue("trade_date", line).CompareTo(TrDate.Value.ToString("yyyy/MM/dd")) != 0 )
                    {
                        MessageBox.Show("Trading date mismatch. Please check the trading date and the data file.");
                        file.Close();
                        return;
                    }*/

                    if (count == ((count / (lines.Length / 100)) * (lines.Length / 100)))
                        ProBar_();


                    String JointACNo = GetValue("joint_ac_no", line);
                    if (JointACNo.Length == 1)
                        JointACNo = "0" + JointACNo;

                    String ClientCode = "";
                    if (FileType == "trades")
                    {
                        ClientCode =    GetValue("participant id", line) + "-" +
                                        GetValue("client_prefix", line) + "-" +
                                        GetValue("client_suffix", line) + "-" +
                                        JointACNo;
                    }
                    else
                    {
                        ClientCode =    BROKER_CODE + "-" +
                                        GetValue("client_prefix", line) + "-" +
                                        GetValue("client_suffix", line) + "-" +
                                        JointACNo;
                    }
                    

                    //LogBox.AppendText(ClientCode + "\n");
                   
                    
                    if (!ClientsList.Contains(ClientCode))
                    {
                        continue;
                    }
                    RecCount++;
                    file.WriteLine(line);

                }
                //System.Console.WriteLine("No of records :" + count);
                file.Close();
                LogBox.AppendText(RecCount + " recodes were written to the " + AgentCode + "_"+ FileType +"_" + date + ".txt" + " file.\n");

            }
            catch (Exception fileEx)
            {
                MessageBox.Show(fileEx.Message);
            }
        }



        static String GetValue(String ClmName, String Line)
        {
            String value = "";
            value = Line.Substring(mapOffset[ClmName], mapSize[ClmName]);
            return value.Trim();
        }


        void ReadCDSTranDataFile()
        {
            int count = 0;
            try
            {
                List<String> ClientsList = ClientsUnderAgent("LOLC"); 
                string[] lines = System.IO.File.ReadAllLines(CDSDataTxtBox.Text);

                SymbolList.Clear();
                SymbolList = SecurityServices.GetSecSymbolList();

                foreach (string line in lines)
                {
                    //System.Console.WriteLine("No of Lines :" + line.Length);

                    count++;
                    
                    //Checking the length of a line
                    if (line.Length != LineWidth)
                    {
                        MessageBox.Show("Error in Line " + count + " of the ats2_ttr data file.\n" +
                                       "Please check the file and try again.");
                        return;

                    }       

                    //Trading date has to be matched with the date in the file.
                    //if (GetValue("trade_date", line).CompareTo(TrDate.Value.ToString("yyyy/MM/dd")) != 0 )
                    //{
                    //    MessageBox.Show("Trading date mismatch");
                    //    return;
                    //}

                    if (count == ((count / (lines.Length / 100)) * (lines.Length / 100)))
                        ProBar_();

                    String JointACNo = GetValue("joint_ac_no", line);
                    if (JointACNo.Length == 1)
                        JointACNo = "0" + JointACNo;

                    String ClientCode = BROKER_CODE + "-" +
                                        GetValue("client_prefix", line) + "-" +
                                        GetValue("client_suffix", line) + "-" +
                                        JointACNo;
                    //Console.WriteLine(ClientCode);
                    if (!ClientsList.Contains(ClientCode))
                    {
                        continue;
                    }


                    String CompanySymbol = GetValue("company_id", line) + "-" +
                                            GetValue("main_type", line) + "-" +
                                            GetValue("sub_type", line);

                    UpdateSecurity(CompanySymbol);
              
                    Updateportfolio(ClientCode, CompanySymbol, Int32.Parse(GetValue("quantity", line)));               
           
                    LogBox.AppendText(ClientCode + "\n");
                                        
                }
                System.Console.WriteLine("No of ele :" + mapOffset.Count() + "   " + count);
            }
            catch (Exception fileEx)
            {
                MessageBox.Show(fileEx.Message);
            }

        }

        private void progressBar1_Click(object sender, EventArgs e)
        {

        }

        public void ProBar_()
        {
            progressBar1.Increment(1);
            
            if (progressBar1.Value == progressBar1.Maximum)
            {    
                //MessageBox.Show("File Loading Done !");                            
            }
        }

        private void button1_Click_2(object sender, EventArgs e)
        {
            if (AgentCheckBox.CheckedItems.Count == 0)
            {
                MessageBox.Show("Select at least one Agent.", "Error");
                return;
            }
            if (AtsDataTxtBox.Text.Equals(""))
            {
                MessageBox.Show("File Path is empty.", "Error");
                return;
            }

            
            ReadTradeHdrFile(TrHdrFile, 6);
            foreach(object itemChecked in AgentCheckBox.CheckedItems) 
            {
                //MessageBox.Show(itemChecked.ToString());
                GenerateDataFiles(itemChecked.ToString(), "trades", AtsDataTxtBox.Text);
            }
        }

        public List<String> ClientsUnderAgent(String AgentCode)
        {
            List<String> ClientsList = new List<String>();
            ClientsList.Add("DSA-750062067-VN-00");
            ClientsList.Add("DSA-6020-FI-00");
            ClientsList.Add("DSA-702132266-VN-00");

            return ClientsList;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                String[] TaxsFees = ConfigurationSettings.AppSettings.AllKeys;
                CDSDataTxtBox.Text = TaxsFees[1];
            }
            catch(Exception er)
            {
                MessageBox.Show("Error in App.config file.");
            }                      

        }

        private void TrUpload_Click(object sender, EventArgs e)
        {
            ReadTradeHdrFile(TrHdrFile, 6);
            ReadTradeFile("All");
        }

        private void LogBox_TextChanged(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {
            ReadTradeHdrFile(CDSTranHdrFile, 3);
            ReadCDSTranDataFile();
        }

        private void TrCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void AtsDataTxtBox_TextChanged(object sender, EventArgs e)
        {

        }


        private void UpdateSecurity(String CompanySymbol)
        {
            //Security SecObj = SecurityServices.GetSecurityBySymbol(CompanySymbol);

            if (!SymbolList.Contains(CompanySymbol))
            {
                Security SecObj = new Security();
                SecObj.Name = CompanySymbol;
                SecObj.Symbol = CompanySymbol;
                SecObj.MarketValue = 0;
                SecObj.MarginPercentage = 100;
                SecurityServices.Add(SecObj);
            }

        }

        private void Updateportfolio(String ClientCode,String CompanySymbol, int Quantity)
        {
            Portfolio ClPort = PortfolioServices.GetPortfolioByCodeAndSymbol(ClientCode, CompanySymbol);

            if (ClPort == null)
            {
                ClPort = new Portfolio();
                ClPort.Code = ClientCode;
                ClPort.Symbol = CompanySymbol;     
                ClPort.Quantity = Quantity + ClPort.Quantity;
                
                PortfolioServices.Add(ClPort);
            }
            else
            {
                ClPort.Quantity = ClPort.Quantity + Quantity;
                PortfolioServices.Update(ClPort);

            }    

        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            if (AgentCheckBox.CheckedItems.Count == 0)
            {
                MessageBox.Show("Select at least one Agent.", "Error");
                return;
            }
            if (CDSDataTxtBox.Text.Equals(""))
            {
                MessageBox.Show("File Path is empty.", "Error");
                return;
            }
            

            ReadTradeHdrFile(CDSTranHdrFile, 3);
            foreach (object itemChecked in AgentCheckBox.CheckedItems)
            {
                //MessageBox.Show(itemChecked.ToString());
                GenerateDataFiles(itemChecked.ToString(), "CDSTran", CDSDataTxtBox.Text);
            }
        }



    }
}
